package luz.javaproxy.gui;


import java.util.List;

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;

import luz.javaproxy.common.Tuple;
import luz.javaproxy.plugin.PluginInterface;
import luz.javaproxy.plugin.PluginMgr;


public class PluginTable extends JTable{
	private static final long serialVersionUID = 534648762781480107L;
	private final MyTableModel model;

	public PluginTable(){
		this(null);
	}
	
	public PluginTable(PluginMgr mgr){
		super();
		
		model=new MyTableModel(mgr);
		this.setModel(model);
		this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		this.getColumnModel().getColumn(1).setMinWidth(50);
		this.getColumnModel().getColumn(1).setMaxWidth(50);
	}
	
	public PluginInterface getSelectedPlugin() {
		int row = this.getSelectedRow();
		if (row!=-1)
			return model.getPluginAt(row);
		else
			return null;
	}
	

	public void setSelectedPlugin(int current) {
		this.getSelectionModel().setSelectionInterval(current, current);
		
	}
	
	public void updateTable(){
		model.fireTableDataChanged();
	}
	
	private static class MyTableModel extends AbstractTableModel {
		private static final long serialVersionUID = 7780019195084742274L;
		private String[] columnNames = {"Name", "Enabled"};
	    private List<Tuple<PluginInterface, Boolean>> plugins;
	    private PluginMgr mgr;
	    
	    public MyTableModel(PluginMgr mgr){
	    	this.mgr=mgr;
    		this.plugins=mgr.getPlugins();
	    }
	    
	    @Override
	    public int getColumnCount() {
	        return columnNames.length;
	    }
	    
	    @Override
	    public int getRowCount() {
	        return plugins.size();
	    }
	    
	    @Override
	    public String getColumnName(int col) {
	        return columnNames[col];
	    }
	    
	    @Override
	    public Object getValueAt(int row, int col) {
	    	switch (col){
	    		case 0:
	    			PluginInterface p = plugins.get(row).getFirst();
	    			return p==null?null:p.getClass().getSimpleName();
	    		case 1: 
	    			return plugins.get(row).getSecond();

	    		default: return null;
	    	}
	    }
	    	    
	    public PluginInterface getPluginAt(int row) {
	    	return plugins.get(row).getFirst();
	    }
	    
		@Override
	    @SuppressWarnings("unchecked")
	    public Class getColumnClass(int c) {
	    	Object r = getValueAt(0, c);
	        return r!=null?r.getClass():Object.class;
	    }
	    
	    @Override
	    public boolean isCellEditable(int row, int col) {
	    	return (col==1);
        }
	    
	    @Override
        public void setValueAt(Object value, int row, int col) {
	    	mgr.setPluginEnabled(getPluginAt(row), (Boolean)value);
            fireTableCellUpdated(row, col);
        }

	}







	
}
